package com.yt.base.util;

import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * Created by lizhiguo on 16-5-9.
 */
public class FileUploadUtil {
	public static String upload(File source, String sourceFileName, String uploadPath) throws IOException {
		String destName = generateFileName(sourceFileName);
		File destination = new File(uploadPath);
		if (!destination.exists()) {
			destination.mkdirs();
		}
		FileUtils.copyFile(source, new File(uploadPath + "/" + destName));
		return destName;
	}

	public static String upload(File source, String sourceFileName, String uploadPath, Long temp) throws IOException {
		String destName = sourceFileName;
		File destination = new File(uploadPath + "/" + destName);
		FileUtils.copyFile(source, destination);
		return destName;
	}

	/**
	 * 保存在本地
	 * @param source
	 * @param uploadPath
	 * @return
	 * @throws IOException
	 */
	public static String upload(MultipartFile source, String uploadPath) throws IOException {
		String destName = generateFileName(source.getOriginalFilename());
		File destination = new File(uploadPath);
		if (!destination.exists()) {
			destination.mkdirs();
		}
		source.transferTo(new File(uploadPath + "/" + destName));
		return destName;
	}

	// 为上传文件自动分配文件名称，避免重复
	public static String generateFileName(String fileName) {
		// 获得当前时间
		DateFormat format = new SimpleDateFormat("yyMMddHHmmss");

		// 转换为字符串
		String formatDate = format.format(new Date());

		// 随机生成文件编号
		int random = new Random().nextInt(10000);

		// 获得文件后缀名称
		int position = fileName.lastIndexOf(".");

		String extension = fileName.substring(position);

		// 组成一个新的文件名称
		return formatDate + random + extension;
	}

	public static boolean checkFileExt(String fileName, String allowExts) {
		String ext = fileName.substring(fileName.lastIndexOf("."));
		if (allowExts.indexOf(ext) != -1) {
			return true;
		}
		return false;
	}

	public static void removeFile(String sourceFileName, String uploadPath) {
		File destination = new File(uploadPath + File.separator + sourceFileName);
		if (destination.exists()) {
			destination.delete();
		}
	}
}
